package com.ruoyi.common.utils.sign;
import javax.crypto.Cipher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import javax.crypto.spec.SecretKeySpec;
import javax.validation.constraints.Size;

/**
 * @Author xiaom
 * @Date 2020/12/16 11:51
 * @Version 1.0.0
 * @Description <>
 **/
public class AES {

    /**
     * 默认的字符编码
     */
    private static final String DEFAULT_CHARSET = "utf-8";

    /**
     * 算法
     */
    private static String ALGORITHM = "AES";

    private static String sKey = "9ce62c1836d128cfc875c9026db7564c";

    private static final Logger logger = LoggerFactory.getLogger(AES.class);
    /**
     * 算法/模式/填充
     **/
    private static final String CipherMode = "AES/ECB/PKCS5Padding";

    public static void main(String args[]) throws Exception {
        String enStr = encryptAES("陈小小");
        System.out.println(enStr);
        String des = "DEhM1ynktgfZ2x1h/ilFP/VptKr+X04+eIk/1/i68ReUeTtuwdnzzMcJ80UAd+dOg52CFmBG5nl+rLZ5JB8r96fzXCN37sCGtAfB5SPFPlAQ0KPJrQy932GPAqyjNZgIm30pv7iyZA22hK4cqEmlwfYMjces5j8yHg7UvFGu5EUruaA8M3ny8vjDA0FSfusS4hA1sAxKEo/ib9x88p10HUCuDiONtdI0NQNVjqPnvZWDLf9UI+Z9omrVoSzjHX1TPZxESnIy73qbKNI5S0LqAEqUPX3vGqXOUO27B0uI7i+kAq4AZSK6rVoJHfTNL+Z30zwWn/EKMU5iSmDUp/hvC7WTBiqLRDQCFmZskBDsMNMZvff9WO/+ZC9L3xg2Q1waiTZ26Jk4RxRIgvSUA+WL336Oce4tYybGXBtaY6Z41hYYZz8k2B30JxznudPraaK5qPzsuB72SKoEh9878Srh0FNIjzG5Y9swxeaXgmA0tyhxKAGKB/Q9sLSiQ6+FyKG0t5T6n5IlqL/7BYi4D2BWMpfuBQY/pogkdxghO5VLFWa05/FyxrsUp6FhOXhdXouFCQnxMyCe23t09USEAJJbbsU6owjgDbXLU5i6jXz+zCOH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6sjo8EH7Y2RSmiXxPF+1nx";
        System.out.println(decryptAES(des));
    }

    public static String encryptAES(String data) throws Exception {
        try {
            byte[] raw = sKey.getBytes(DEFAULT_CHARSET);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(data.getBytes(DEFAULT_CHARSET));

            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception ex) {
            logger.error("AES加密失败", ex);
            return null;
        }
    }

    public static String decryptAES(String data) throws Exception {
        try {
            byte[] raw = sKey.getBytes(DEFAULT_CHARSET);
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            // 先用base64解密
            byte[] encryptedArr = Base64.getDecoder().decode(data);
            byte[] original = cipher.doFinal(encryptedArr);
            return new String(original, DEFAULT_CHARSET);
        } catch (Exception ex) {
            logger.error("AES解密失败", ex);
            return null;
        }
    }

}
